package router

import (
	"fmt"
	"gin/controller"
	"gin/middleware"
	sessionsStore "gin/session"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	etcd "github.com/teamones-open/etcd-discovery"
	"github.com/teamones-open/etcd-discovery/common"
	register_route "github.com/teamones-open/go-register-route"
)

func InitRouter() {
	router := gin.Default()

	// 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404
	router.Use(middleware.Cors())

	// 使用 session(cookie-based)
	router.Use(sessions.Sessions("go_clickhouse", sessionsStore.Store))

	var AuthController controller.Auth
	router.GET("/", AuthController.HealthyReturn)

	var TenantController controller.Tenant
	tenant := router.Group("bi")
	{
		tenant.POST("/get_tenant_work_base", TenantController.GetWorkBase)
	}

	var ProjectController controller.Project
	project := router.Group("bi")
	{
		project.POST("/get_ip_project_list", ProjectController.GetInProgressProjectList)
		project.POST("/get_project_all_spend", ProjectController.GetAllSpend)
	}

	var TaskController controller.Task
	task := router.Group("bi")
	{
		task.POST("/get_user_work_rank", TaskController.WorkRank)
		task.POST("/get_task_statistics", TaskController.Statistics)
		task.POST("/get_task_version_trend", TaskController.VersionTrend)
		task.POST("/get_task_step_category_statistics", TaskController.StepCategoryStatistics)
		task.POST("/count_version_by_step_category", TaskController.CountVersionByDepartment)
		task.POST("/get_task_finance_statistics", TaskController.FinanceStatistics)
		task.POST("/get_task_requires_statistics", TaskController.RequiresStatistics)
		task.POST("/count_unfinished_task_work_order", TaskController.CountUnfinishedTaskWorkOrder)
		task.POST("/count_completed_task", TaskController.CountCompletedTask)
		task.POST("/count_ip_task", TaskController.CountInProgressTask)
		task.POST("/count_overdue_task", TaskController.CountUnfinishedAndOverdueTask)
		task.POST("/get_task_workload_statistics", TaskController.GetTaskWorkloadStatistics)
		task.POST("/get_wait_assign_step_category_count", TaskController.GetWaitAssignStepCategoryCount)
	}

	var TaskRepairController controller.TaskRepair
	taskRepair := router.Group("task_repair").Use(middleware.Auth())
	{
		// 返修受影响的任务
		taskRepair.POST("/get_effected_task", TaskRepairController.GetEffectedTask)
		// 任务上游任务列表
		taskRepair.POST("/get_upstream_tasks", TaskRepairController.GetUpstreamTasks)
		//查询受影响多项目的分组任务
		taskRepair.POST("/get_multi_project_effected_group_task", TaskRepairController.GetMultiProjectEffectedGroupTask)
	}

	taskOverView := router.Group("bi").Use(middleware.Auth())
	{
		taskOverView.POST("/todo_task_overview", TaskController.TodoTaskOverview)
		taskOverView.POST("/task_survey", TaskController.TaskSurvey)                       //生产统计报表
		taskOverView.POST("/task_survey_detail_list", TaskController.TaskSurveyDetailList) //生产统计报表详情列表
	}

	// 制片管理
	var ProductionManageController controller.ProductionManage
	productionList := router.Group("bi").Use(middleware.Auth())
	{
		productionList.POST("/production_manage_list", ProductionManageController.List) // 制片管理-列表
		productionList.POST("/production_manage_info", ProductionManageController.Info) // 制片管理-详情
	}
	productionManage := router.Group("production_manage").Use(middleware.Auth())
	{
		productionManage.POST("/today_count", ProductionManageController.TodayCount)                              // 制片管理-今日统计
		productionManage.POST("/progress_count", ProductionManageController.ProgressCount)                        // 制片管理-进度统计
		productionManage.POST("/get_plan_todo_task_progress", ProductionManageController.GetPlanTodoTaskProgress) //获取当前月计划代办任务进度
		productionManage.POST("/episode_task_count", ProductionManageController.EpisodeTaskCount)                 //获取集下任务进度统计
		productionManage.POST("/review_feedback_count", ProductionManageController.ReviewFeedbackCount)           //获取集下任务进度统计
		productionManage.POST("/director_star", ProductionManageController.DirectorStar)                          // 导演关注
		productionManage.POST("/total_task_count", ProductionManageController.TotalTaskCount)                     // 导演关注
	}

	// 周例会任务报表
	taskWeekMeeting := router.Group("bi").Use(middleware.Auth())
	{
		taskWeekMeeting.POST("/task_completion", TaskController.TaskCompletion)          // 任务完成情况
		taskWeekMeeting.POST("/work_order_situation", TaskController.WorkOrderSituation) // 工单情况
		taskWeekMeeting.POST("/task_completion_list", TaskController.TaskCompletionList) // 任务完成详情
	}

	// 排期详情统计
	var ScheduleInfoController controller.ScheduleInfo
	scheduleInfo := router.Group("schedule").Use(middleware.Auth())
	{
		scheduleInfo.POST("/deliver_list", ScheduleInfoController.DeliverList)                                                                          // 交付数量统计
		scheduleInfo.POST("/count", ScheduleInfoController.Count)                                                                                       // 交付数量统计
		scheduleInfo.POST("/step_category_devoted_list", ScheduleInfoController.StepCategoryDevotedList)                                                // 本月环节已投入
		scheduleInfo.POST("/schedule_task_count", ScheduleInfoController.ScheduleTaskCount)                                                             // 排期任务统计
		scheduleInfo.POST("/schedule_status_task_count", ScheduleInfoController.ScheduleStatusTaskCount)                                                // 排期状态任务统计
		scheduleInfo.POST("/schedule_non_standard_project_task_completion_count", ScheduleInfoController.ScheduleNonStandardProjectTaskCompletionCount) // 非标准项目排期任务查询
		scheduleInfo.POST("/schedule_non_standard_task_member_count", ScheduleInfoController.ScheduleNonStandardTaskMemberCount)                        // 非标准项目排期任务待办成员查询
		scheduleInfo.POST("/schedule_non_standard_task_list", ScheduleInfoController.ScheduleNonStandardTaskList)                                       // 根据用户ID查询非标准项目任务待办
		scheduleInfo.POST("/non_standard_step_category_devoted_list", ScheduleInfoController.NonStandardStepCategoryDevotedList)                        // 非标准本月环节已投入
	}

	// 需求管理
	var NeedController controller.NeedManage
	needManage := router.Group("project").Use(middleware.Auth())
	{
		needManage.POST("/asset_total_list", NeedController.AssetTotalList) // 资产统计列表
		needManage.POST("/shot_total_list", NeedController.ShotTotalList)   // 镜头统计列表
	}

	var ReviewRequestController controller.ReviewRequest
	reviewRequest := router.Group("bi")
	{
		reviewRequest.POST("/get_review_record", ReviewRequestController.ReviewRecord)
	}

	var FinanceController controller.Finance
	finance := router.Group("bi").Use(middleware.Auth())
	{
		finance.POST("/finance_hour_count", FinanceController.FinanceHourCount)
		finance.POST("/finance_asset_hour_count", FinanceController.FinanceAssetHourCountV3)
		finance.POST("/v3/finance_asset_hour_count", FinanceController.FinanceAssetHourCountV3)
		finance.POST("/finance_asset_hour_count_lock", FinanceController.FinanceAssetHourCountLock)
	}

	var UserController controller.User
	user := router.Group("bi")
	{
		user.POST("/get_user_task_workload", UserController.GetUserTaskWorkloadStatistics)
	}

	taskGroup := router.Group("task").Use(middleware.Auth())
	{
		taskGroup.POST("/check_shot_task_done", TaskController.CheckShotTaskDone)
		taskGroup.POST("/user_count_detail", TaskController.UserCountDetail)                // 用户任务统计
		taskGroup.POST("/my_responsible_task_list", TaskController.MyResponsibleTaskList)   // 我负责的任务-list
		taskGroup.POST("/my_responsible_task_count", TaskController.MyResponsibleTaskCount) // 我负责的任务-count

		taskGroup.POST("/user_list", TaskController.UserList)     // 人员列表
		taskGroup.POST("/count", TaskController.Count)            // 任务统计
		taskGroup.POST("/delay_count", TaskController.DelayCount) // 任务统计
	}

	var DepartmentController controller.Department
	department := router.Group("department").Use(middleware.Auth())
	{
		department.POST("/delete_check", DepartmentController.DeleteCheck) // 部门删除检查
	}

	//通过实体获取实体关联其他实体信息
	var EntityController controller.Entity
	entity := router.Group("entity").Use(middleware.Auth())
	{
		entity.POST("/get_entity_relation_info", EntityController.GetEntityRelationInfo)                          // 通过实体获取实体关联其他实体信息
		entity.POST("/get_asset_relation_shot_count", EntityController.GetAssetRelationShotCount)                 // 获取资产关联镜头统计
		entity.POST("/get_asset_relation_shot_ids", EntityController.GetAssetRelationShotIds)                     // 获取资产关联的镜头id
		entity.POST("/get_asset_relation_shot_list", EntityController.GetAssetRelationShotList)                   // 获取资产关联的镜头列表
		entity.POST("/get_multiple_entity_relation_ids", EntityController.GetMultipleEntityRelationIds)           // 获取多个实体的关联ids
		entity.POST("/get_multiple_entity_relation_count", EntityController.GetMultipleEntityRelationCount)       // 获取实体的关联统计
		entity.POST("/get_asset_relation_shot_task_card_list", EntityController.GetAssetRelationShotTaskCardList) // 获取资产任务卡片关联的镜头列表
	}

	var WorkTimeController controller.WorkTime
	workTime := router.Group("work_time").Use(middleware.Auth())
	{
		workTime.POST("/get_tenant_user_statistics", WorkTimeController.GetTenantUserStatistics)
		workTime.POST("/export_user_statistics", WorkTimeController.ExportUserStatistics) // 导出工时报表
		//plan_node_report_list
		workTime.POST("/plan_node_report_list", WorkTimeController.PlanNodeReportList) // 日报-备注列表

	}

	// bi v2
	biv2 := router.Group("bi/v2").Use(middleware.Auth())
	{
		biv2.POST("/project_list", ProjectController.ProjectListV2)                                       // 项目列表
		biv2.POST("/project_man_resource_distribution", ProjectController.ProjectManResourceDistribution) // 项目人力资源分布情况
		biv2.POST("/project_detail", ProjectController.ProjectDetail)                                     // 项目详情
		biv2.POST("/project_task_submit_count_by_date", ProjectController.ProjectTaskSubmitCountByDate)   // 项目任务提交趋势
		biv2.POST("/project_task_done_grouped_count", ProjectController.ProjectTaskDoneGroupedCount)      // 项目任务完成数量分组统计
		biv2.POST("/project_step_category_done_count", ProjectController.ProjectStepCategoryDoneCount)    // 项目环节产出情况
		biv2.POST("/project_asset_preview_check", ProjectController.ProjectAssetPreviewCheck)             // 项目资产巡检
		biv2.POST("/project_inprogress_episode", ProjectController.ProjectInprogressEpisode)              // 项目进行中剧集
	}

	var NoteEntityRelationController controller.NoteEntityRelation
	NoteEntityRelation := router.Group("note_entity_relation").Use(middleware.Auth())
	{
		NoteEntityRelation.POST("/get_asset_feedback_affected_shot_count", NoteEntityRelationController.GetAssetFeedbackAffectedShotCount)
		NoteEntityRelation.POST("/get_shot_feedback_step_category_count", NoteEntityRelationController.GetShotFeedbackStepCategoryCount)
	}

	// 工作台管理
	var WorkbenchController controller.Workbench
	workbench := router.Group("workbench").Use(middleware.Auth())
	{
		workbench.POST("/global_abnormal_count", WorkbenchController.GlobalAbnormalCount)      // 全局异常
		workbench.POST("/personal_task_count", WorkbenchController.PersonalTaskCount)          // 个人任务
		workbench.POST("/step_category_task_count", WorkbenchController.StepCategoryTaskCount) // 环节任务

		workbench.POST("/group_upstream_delivery_count", WorkbenchController.GroupUpstreamDeliveryCount)    // 组内上游交付情况
		workbench.POST("/group_plan_done_count", WorkbenchController.GroupPlanDoneCount)                    // 组内完成情况
		workbench.POST("/group_delivery_count", WorkbenchController.GroupDeliveryCount)                     // 组内交付情况
		workbench.POST("/group_abnormal_add_count", WorkbenchController.GroupAbnormalAddCount)              // 组内异常 新增任务
		workbench.POST("/group_abnormal_work_order_count", WorkbenchController.GroupAbnormalWorkOrderCount) // 组内异常 待处理工单
		workbench.POST("/group_abnormal_delay_task_count", WorkbenchController.GroupAbnormalDelayTaskCount) // 组内异常 延期任务

		workbench.POST("/episode_detail", WorkbenchController.EpisodeDetail)                                            // 工作台 剧集封板详情
		workbench.POST("/step_category_inprogress_episode_list", WorkbenchController.StepCategoryInprogressEpisodeList) // 工作台 环节进行中剧集列表
		workbench.POST("/step_category_reviewing_episode_list", WorkbenchController.StepCategoryReviewingEpisodeList)   // 工作台 环节审核中的剧集情况
		workbench.POST("/step_category_seal_episode_list", WorkbenchController.StepCategorySealEpisodeList)             // 工作台 环节封板剧集情况查询
		workbench.POST("/episode_seal_show_list", WorkbenchController.EpisodeSealShowList)                              // 工作台 剧集封板播出情况列表
		workbench.POST("/making_overview", WorkbenchController.MakingOverview)                                          // 工作台 制作情况概览
		workbench.POST("/today_abnormal_task_count", WorkbenchController.ToDayAbnormalTaskCount)                        // 工作台 今日异常任务统计

	}
	// 项目任务进度
	var projectTaskProgressController controller.ProjectTaskProgress

	projectTaskProgress := router.Group("project_task_progress").Use(middleware.Auth())
	{
		projectTaskProgress.POST("/get_task_delivery_count", projectTaskProgressController.GetTaskDeliveryCount)       //交付统计
		projectTaskProgress.POST("/get_task_done_count", projectTaskProgressController.GetTaskDoneCount)               //完成统计
		projectTaskProgress.POST("/get_work_load_count", projectTaskProgressController.GetWorkLoadCount)               //产能统计
		projectTaskProgress.POST("/get_step_category_progress", projectTaskProgressController.GetStepCategoryProgress) //产能统计

	}
	// 上报路由
	err := RegisterRoutes(router)
	if err != nil {
		fmt.Println(err.Error())
	}

	port := viper.GetString("server.port")
	if port != "" {

		// 注册服务到ETCD
		etcdStatus := viper.GetString("etcd.status")
		if etcdStatus == "active" {
			etcdHost := viper.GetString("etcd.host")
			etcdPort := viper.GetString("server.port")
			etcdServerName := viper.GetString("etcd.serverName")
			if viper.GetString("etcd.mode") == "release" {
				common.SetMode("release")
			}
			err := etcd.RegisterServer(etcdHost, etcdPort, etcdServerName)
			if err != nil {
				fmt.Println(err.Error())
			}
		}

		panic(router.Run(":" + port))
	}

	panic(router.Run())
}

// 路由上报注册
func RegisterRoutes(router *gin.Engine) (err error) {
	Routes := router.Routes()
	url := viper.GetString("rotueServer.url")
	serverName := viper.GetString("etcd.serverName")
	err = register_route.Register(Routes, url, serverName)
	return err
}
